<template>
  <div>
    <div class="threeLevelMain">
      <!-- 报价容器 -->
      <div class="quoteContainer">
        <!-- 报价顶部信息 -->
        <div class="quote_info clearfix">
          <h3 class="h3_title">报价单</h3>
          <div class="quote_itemBox">
            <div class="quote_item">
              <span class="quote_label">客户名称：</span>
              <p class="quote_p">{{ form.custName }}</p>
            </div>
            <div class="quote_item">
              <span class="quote_label">联系方式：</span>
              <p class="quote_p">{{ form.phoneNumber }}</p>
            </div>
          </div>
          <div class="quote_itemBox">
            <div class="quote_item">
              <span class="quote_label">项目要求：</span>
              <p class="quote_p">{{ form.projectRequirement }}</p>
            </div>
            <div class="quote_item">
              <span class="quote_label">备注：</span>
              <p class="quote_p">{{ form.remark }}</p>
            </div>
          </div>
        </div>
        
        <img src="" class="avatar" />
        <!-- 设备选取表格 -->
        <div class="quote_table clearfix">
          <el-table
            border
            class="table_domQuote"
            ref="tableDomQuote"
            size="small"
            :data="tableData"
            style="width: 100%"
          >
            <el-table-column
              prop="number"
              width="80"
              label="序号"
              align="center"
            ></el-table-column>
            <el-table-column
              label="设备名称"
              prop="name"
              align="center"
            ></el-table-column>
            <el-table-column
              label="数量"
              prop="num"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="salePrice"
              label="销售单价"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="saleTotal"
              label="销售合计"
              align="center"
            ></el-table-column>
            <el-table-column
              label="备注"
              prop="remark"
              align="center"
            ></el-table-column>
            <div slot="append">
              <div class="quoteTable">
                <span class="quoteTable_sp1">合计：</span>
                <span class="quoteTable_sp1">{{ form.totalPrice }}</span>
              </div>
            </div>
          </el-table>
        </div>
      </div>
      <!-- 审核备注容器 -->
      <div class="reasonBox clearfix">
        <div class="title_checkReason">审核备注：</div>
        <div class="checkReasonMain">
          <div class="p_box">
            <p class="p_checkReason">{{ form.checkReason }}</p>
          </div>
        </div>
      </div>
      <!-- 底部按钮容器 -->
    </div>
    <div class="botmBtnContainer">
      <button @click="exportWord" size="small" type="primary">导出word</button>
      <button @click="pageToPdf('test')" size="small" type="primary">
        导出pdf
      </button>
      <button @click="pageToHtml('test')" size="small" type="primary">
        导出Html
      </button>

      <!-- <button @click="exportExcelClick" size="small" type="primary">导出excel</button> -->
    </div>
  </div>
</template>
<script>
import JSZipUtils from "jszip-utils";
import docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
import PizZip from "pizzip";

import Html2Canvas from "html2canvas";
import JsPdf from "jspdf";
export default {
  name: "home",
  data() {
    return {
      form: {
        custName: "杰斯", // 客户姓名
        phoneNumber: "138xxxxxxxx", // 联系方式
        projectRequirement: "为了更美好的明天而战", // 项目要求
        totalPrice: 140, // 合计报价
        remark: "QEWARAEQAAAAAAAAA", // 备注
        checkReason: "同意",
        // 审核备注
      },
      echartData: {},
      tableData: [],
    };
  },
  created() {
    this.echartData = {
      lenged: ["小米", "小张"],
      age: [18, 22],
    };
    this.tableData = [
      {
        number: 1, // 序号
        name: "设备1", // 设备名称
        num: 1, // 数量
        salePrice: 10, // 销售单价
        saleTotal: 10, // 销售合计
        remark: "啦啦啦",
        image:
          "",
      },
      {
        number: 1, // 序号
        name: "设备1", // 设备名称
        num: 1, // 数量
        salePrice: 10, // 销售单价
        saleTotal: 10, // 销售合计
        remark: "啦啦啦",
        image:
          "",
      },
      {
        number: 1, // 序号
        name: "设备1", // 设备名称
        num: 1, // 数量
        salePrice: 10, // 销售单价
        saleTotal: 10, // 销售合计
        remark: "啦啦啦",
        image:
          "",
      },
    ];
  },
  computed: {
    option() {
      return echartConfig(this);
    },
    columns() {
      return tableConfig(this);
    },
  },

  methods: {
    pageToPdf(name) {
      Html2Canvas(document.getElementsByClassName("threeLevelMain")[0], {
        allowTaint: true,
        taintTest: false,
        height: document.getElementsByClassName("threeLevelMain")[0]
          .scrollHeight,
        width: document.getElementsByClassName("threeLevelMain")[0].scrollWidth, // 为了使横向滚动条的内容全部展示，这里必须指定
      }).then((canvas) => {
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;
        let pageHeight = (contentWidth / 555.28) * 841.89;
        let leftHeight = contentHeight;
        let position = 12;
        let imgWidth = 555.28;
        let imgHeight = (555.28 / contentWidth) * contentHeight;
        let pageData = canvas.toDataURL("image/jpeg", 1.0);
        // 第一个参数： l：横向  p：纵向
        // 第二个参数：测量单位（"pt"，"mm", "cm", "m", "in" or "px"）
        // 第三个参数：可以是下面格式，默认为“a4”
        let PDF = new JsPdf("", "pt", "a4");
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, "PNG", 20, 0, imgWidth, imgHeight);
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, "PNG", 20, position, imgWidth, imgHeight);
            leftHeight -= pageHeight;
            position -= 841.89;
            if (leftHeight > 0) {
              PDF.addPage();
            }
          }
        }
        PDF.save(name + ".pdf");
      });
    },
    pageToHtml(name) {
      Html2Canvas(document.getElementsByClassName("threeLevelMain")[0], {
        allowTaint: true,
        taintTest: false,
        height: document.getElementsByClassName("threeLevelMain")[0]
          .scrollHeight,
        width: document.getElementsByClassName("threeLevelMain")[0].scrollWidth, // 为了使横向滚动条的内容全部展示，这里必须指定
      }).then((canvas) => {
        let pageData = canvas.toDataURL("image/jpeg", 1.0);
        let html = `<!DOCTYPE html>
                <html>
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width,initial-scale=1.0">
                    <title>${name}</title>
                </head>
                <body>
                    <div style="display: flex;justify-content: center;">
                      <img style="width: 90%;" src=${pageData} />
                    </div>
                </body>
                </html>`;
        let eleLink = document.createElement("a");
        eleLink.style.display = "none";
        let blob = new Blob([html]);
        let url = URL.createObjectURL(blob, {
          type: "text/plain;charset=utf-8",
        });
        eleLink.href = url;
        eleLink.download = name + ".html";
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
      });
    },
    // 点击导出word
    base64DataURLToArrayBuffer(dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },
    exportWord: function () {
      let ImageModule = require("docxtemplater-image-module-free");

      // 点击导出word
      let _this = this;
      // 读取并获得模板文件的二进制内容
      JSZipUtils.getBinaryContent(
        "./tempt/input.docx",
        function (error, content) {
          // exportTemplate.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
          // 抛出异常
          if (error) {
            throw error;
          }
          // 图片处理
          let opts = {};
          opts.centered = true; // 图片居中，在word模板中定义方式为{%%image}
          opts.fileType = "docx";
          opts.getImage = function (chartId) {
            return _this.base64DataURLToArrayBuffer(chartId);
          };
          opts.getSize = function () {
            return [200, 200];
          };
          let imageModule = new ImageModule(opts);
          // 创建一个PizZip实例，内容为模板的内容
          let zip = new PizZip(content);
          // 创建并加载docxtemplater实例对象
          let doc = new docxtemplater();
          doc.attachModule(imageModule);
          doc.loadZip(zip);

          // 设置模板变量的值
          doc.setData({
            table: _this.tableData,

            // 获取echarts图片
          });

          try {
            // 用模板变量的值替换所有模板变量
            doc.render();
          } catch (error) {
            // 抛出异常
            let e = {
              message: error.message,
              name: error.name,
              stack: error.stack,
              properties: error.properties,
            };
            throw error;
          }
          // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
          let out = doc.getZip().generate({
            type: "blob",
            mimeType:
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          });
          // 将目标文件对象保存为目标类型的文件，并命名
          saveAs(out, "exportDocx.docx");
        }
      );
    },
  },
};
</script>
<style lang="scss">
* {
  margin: 0;
  padding: 0;
  font-size: 12px;
  font-family: "微软雅黑", "宋体";
  list-style: none;
  box-sizing: border-box;
}

/* // 清除浮动 */
.clearfix:after {
  content: "";
  height: 0;
  line-height: 0;
  display: block;
  clear: both;
  visibility: hidden;
}

.clearfix {
  zoom: 1;
}

.quoteContainer {
  .quote_info {
    width: 800px;
    margin: 0 auto;

    .h3_title {
      float: left;
      width: 100%;
      font-size: 20px;
      line-height: 40px;
      text-align: center;
      margin-bottom: 30px;
    }

    .quote_itemBox {
      float: left;
      width: 100%;
      margin-bottom: 20px;

      .quote_item {
        float: left;
        width: 50%;
        display: flex;

        .quote_label {
          width: 100px;
          text-align: right;
          line-height: 32px;
        }

        .quote_p {
          flex: 1;
          line-height: 32px;
        }
      }
    }
  }

  .quote_table {
    padding: 0 20px;

    .table_domQuote {
      .quoteTable {
        font-size: 14px;
        padding-left: 30px;
        border-top: 1px solid #ebeef5;

        .quoteTable_sp1 {
          display: inline-block;
          line-height: 50px;
        }
      }
    }
  }
}

.reasonBox {
  padding: 0 20px 20px 20px;

  .title_checkReason {
    line-height: 50px;
  }

  .checkReasonMain {
    .p_box {
      border: 1px solid #ebeef5;
      padding: 10px 20px;

      .p_checkReason {
        height: 30px;
        line-height: 30px;
      }
    }
  }
}

/* // 底部按钮 */
.botmBtnContainer {
  text-align: center;
  padding: 20px;
}
</style>